package com.ybkj.daijia.api.driver.v4;

import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.api.common.AesUtil;
import com.ybkj.daijia.api.driver.DeviceInfoData;
import com.ybkj.daijia.api.driver.Error;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.server.event.model.DriverOfflineEvent;
import com.ybkj.daijia.server.event.model.DriverOnlineEvent;
import com.ybkj.daijia.server.freight.Truck;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverApply;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.model.DriverLoginRecord;
import com.ybkj.daijia.server.model.DriverRebate;
import com.ybkj.daijia.server.model.PhoneSmsRecord;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverApplyService;
import com.ybkj.daijia.server.service.DriverHelppayService;
import com.ybkj.daijia.server.service.DriverLoginRecordService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverRebateService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.DriverTimeService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneSmsRecordService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.service.impl.DefaultDriverRebateService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuan.CarType;
import com.ybkj.daijia.server.zhuanxian.Line;
import com.ybkj.daijia.serverUtils.DataUtils;
import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 司机登录相关
 *
 * @author bo
 */
@Controller("DriverAccountControllerV4")
//@RequestMapping(value = "driver/api/rest/v4")
public class DriverAccountController {

    private static final Logger logger = LoggerFactory.getLogger(DriverAccountController.class);
    @Autowired
    PhoneSmsRecordService phoneSmsRecordService;
    @Autowired
    private HttpServletRequest req;
    @Resource
    private DriverService driverService;
    @Autowired

    private DriverTimeService driverTimeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private ErrandService errandService;
    @Autowired
    private FreightService freightService;
    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private DriverLoginService driverLoginService;
    @Autowired
    private DriverApplyService driverApplyService;
    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;
    @Autowired
    private DriverRebateService driverRebateService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private SuperviceService superviceService;
    @Autowired
    private DriverLoginRecordService driverLoginRecordService;
    @Autowired
    private DataUtils dataUtils;
    @Autowired
    private DriverHelppayService helppayService;
    @Autowired
    private DefaultDriverRebateService defaultDriverRebateService;


    /**
     * 司机登陆
     *
     * @param udId
     * @param username
     * @param password
     * @param deviceType
     * @param deviceInfo
     * @param userId
     * @param registrationId
     * @param appversion
     * @param vcode
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "driver/api/rest/v4/login3", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport login3(
        String udId, String username, String password, String deviceType, String deviceInfo,
        String userId, String registrationId, String appversion, String vcode) {
        if (StringUtils.isBlank(udId) || StringUtils.isBlank(username) || StringUtils
            .isBlank(password) ||
            StringUtils.isBlank(deviceType) || StringUtils.isBlank(deviceInfo) ||
            StringUtils.isBlank(appversion)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        return loginFunc2(udId, username, password, deviceType, deviceInfo, userId, registrationId,
            appversion, vcode);
    }


    private ResultTransport loginFunc2(String udId, String username,
        String password, String deviceType, String deviceInfo,
        String userId, String registrationId, String appversion, String code) {
        Driver driver = driverService.findByUsername(username);
        if (null == driver) {
            driver = driverService.findByPhone(username);
        }
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASS_NOT_CORRECT_ERROR);
        }
        //帐号被冻结
        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }
        //如果开启双因子验证,还需要进行验证码验证
        if (settingUtils.get().isDoubleFactor()) {
            //判断验证码是否正确
            PhoneSmsRecord phoneSmsRecord = phoneSmsRecordService
                .findByPhone(driver.getPhone());
            if (null == phoneSmsRecord) {
                return ResultTransport.getErrorBy(ErrorConstant.CODE_ERROR);
            } else {
                if (!phoneSmsRecord.getVcode().equals(code)) {
                    Integer amount = driverLoginService.addCodeIncorrect(driver);
                    if (amount >= 5) {
                        driver.setIsFreeze(true);
                        driverService.updateByPrimaryKey(driver);
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
                    }
                    return ResultTransport.getErrorBy(ErrorConstant.CODE_ERROR);
                }
            }
        }
        Sha256Hash sha256Hash = new Sha256Hash(password);
        if (!sha256Hash.toBase64().equals(driver.getPassword())) {
            Integer amount = driverLoginService.addPasswordIncorrect(driver);
            if (amount >= 5) {
                driver.setIsFreeze(true);
                driverService.updateByPrimaryKey(driver);
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
            }
            return ResultTransport.getErrorBy(ErrorConstantV4.PASS_NOT_CORRECT_ERROR);
        }
        if (StringUtils.isBlank(udId)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.UDID_IS_BLANK);
        }
        boolean driverBindPhone = settingUtils.get().isDriverBindPhone();
        if (driverBindPhone && StringUtils.isNotBlank(driver.getUdid()) && !driver.getUdid().equals(udId)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ACCOUNT_HAS_OTHERDEVICE);
        }
        if (driverBindPhone) {
            List<Driver> byUdid = driverService.findByUdid(udId);
            if (byUdid != null) {
                for (Driver udIdDriver : byUdid) {
                    if (!udIdDriver.getId().equals(driver.getId())) {
                        return ResultTransport.getErrorBy(
                            new Error(ErrorConstantV4.UDID_HAS_EXISTS.getCode(),
                                "0(" + udIdDriver.getUsername() + ")，请联系管理员"));
                    }
                }
            }
        }
        driver.setDeviceType(deviceType);
        driver.setDeviceInfo(deviceInfo);
        driver.setAppVersion(appversion);
        driver.setUserID(userId);
        driver.setRegistrationId(registrationId);
        Map<String, Object> data = driverService.login(driver);
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(data);
        return instance;
    }

    /**
     * 司机免密登陆
     * @record zhyu
     * @param request
     * @param employToken
     * @param mac
     * @param lat
     * @param lng
     * @param imei
     * @param imsi
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/loginRecord", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport loginRecord(HttpServletRequest request, String employToken, String mac,
        Double lat, Double lng, String imei, String imsi) {
        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);
        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }
        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }
        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASS_NOT_CORRECT_ERROR);
        }
        Company company = companyService.findOne(driver.getCompanyId());
        DriverLoginRecord driverLoginRecord = new DriverLoginRecord();
        driverLoginRecord.setDriverId(driver.getId());
        driverLoginRecord.setCompanyId(driver.getCompanyId());
        driverLoginRecord.setDriverPhone(driver.getPhone());
        driverLoginRecord.setDriverRealName(driver.getRealname());
        driverLoginRecord.setDriverUserName(driver.getUsername());
        driverLoginRecord.setIp(request.getRemoteAddr());
        driverLoginRecord.setPort(request.getRemotePort());
        driverLoginRecord.setMac(mac);
        driverLoginRecord.setLat(lat);
        driverLoginRecord.setLng(lng);
        driverLoginRecord.setImei(imei);
        driverLoginRecord.setImsi(imsi);
        driverLoginRecord.setCity(company.getCityName());
        driverLoginRecord.setCooperationAccountType(dataUtils.getCooperationAccountType());
        driverLoginRecord.setBindingPayAccountType("个人");
        driverLoginRecord.setLoginType("手机登录");
        driverLoginRecordService.insertRecord(driverLoginRecord);
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        return instance;
    }

    /**
     * 司机刷新token 频率 半分钟一次
     *
     * @param employToken token令牌
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "driver/api/rest/v4/tokenRefresh", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport tokenRefresh(String employToken) {
        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);
        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }
        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }
        Driver driver = driverService.findOne(driverLogin.getDriverId());
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }
        Calendar calendar = Calendar.getInstance();
        driverLogin.setRefreshDate(calendar.getTime());
        calendar.add(Calendar.MINUTE, DriverLogin.VALID_TIME);
        driverLogin.setDeathDate(calendar.getTime());
        driverLoginService.update(driverLogin);
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        return instance;
    }

    /**
     * 修改司机密码
     *
     * @param oldPass
     * @param newPass
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/modifyPass", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport modifyPass(String employToken, String oldPass, String newPass) {

        logger.debug("recv employToken:{},oldPass:{},newPass:{}", employToken, oldPass, newPass);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(oldPass) || StringUtils
            .isBlank(newPass)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Sha256Hash sha256Hash = new Sha256Hash(oldPass);

            if (!sha256Hash.toBase64().equals(driver.getPassword())) {
                return ResultTransport.getErrorBy(ErrorConstantV4.PASS_NOT_CORRECT_ERROR);
            }

            if (newPass.length() < 4 || newPass.length() > 20 || !newPass
                .matches("^[^\\s&\"<>]+$")) {
                return ResultTransport.getErrorBy(ErrorConstantV4.PASS_FORMAT_ERROR);
            }

            sha256Hash = new Sha256Hash(newPass);
            driver.setPassword(sha256Hash.toBase64());
            driverService.updateByPassword(sha256Hash.toBase64(), driver.getId());

            Calendar calendar = Calendar.getInstance();
            driverLogin.setDeathDate(calendar.getTime());
            driverLoginService.update(driverLogin);

            return ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //密码修改成功

        } catch (Exception e) {
            logger.error("api v4 driver modifyPass error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }


    }

    /**
     * 司机请求设置上班状态
     * @param id
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
//	@RequestMapping(value="onlined",method=RequestMethod.POST)
//	public @ResponseBody ResultTransport onlined(String employToken) {
//
//		logger.debug("recv employToken:{}",employToken);
//
//		if(StringUtils.isBlank(employToken)) {
//			return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
//		}
//
//		DriverLogin driverLogin=driverLoginService.selectByToken(employToken);
//
//		if(null==driverLogin){
//			return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
//		}
//
//		if(System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()){
//			return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
//		}
//
//		Driver driver = driverService.findOne(driverLogin.getDriverId());
//
//		if(null==driver){
//			return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
//		}
//
//		if(driver.getIsFreeze()) { //帐号被冻结
//			return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
//		}
//
//		Setting setting=settingUtils.get();
//		if(driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
//				&& setting.getLowestWorkVirtual()!=0
//				&& driver.getVirtual().doubleValue()<setting.getLowestWorkVirtual()){
//
//			return ResultTransport.getErrorBy(ErrorConstantV4.LOWEST_WORK_VIRTUAL_ERROR);
//		}
//
//		try {
//
//			if(driver.getStatus()==Driver.DRIVER_OFFLINE){
//				driver.setStatus(Driver.DRIVER_ONLINE);
//				driver.setDutyTime(new Date());
//
//				driverService.online(driver);
//
//				DriverOnlineEvent driverOnlineEvent = new DriverOnlineEvent(driver);
//				applicationEventMulticaster.multicastEvent(driverOnlineEvent);
//			}
//
//			driver.setCompany(companyService.findOne(driver.getCompanyId()));
//
//			ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //上班成功
//			instance.setData(driver);
//
//			return instance;
//
//		} catch (Exception e) {
//			logger.error("api v4 driver onlined error: {}",e);
//			return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
//		}
//	}

    /**
     * 设置司机目前为上班状态
     *
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/online", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport online(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) { //帐号被冻结
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Company company = companyService.findOne(driver.getCompanyId());
        if (driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
            && company.getLowestWorkVirtual().doubleValue() != 0
            && driver.getVirtual().doubleValue() < company.getLowestWorkVirtual().doubleValue()) {

            return ResultTransport.getErrorBy(ErrorConstantV4.LOWEST_WORK_VIRTUAL_ERROR);

        }

        try {

            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                driver.setStatus(Driver.DRIVER_ONLINE);
                driver.setDutyTime(new Date());
                driverService.online(driver);

                DriverOnlineEvent driverOnlineEvent = new DriverOnlineEvent(driver);
                applicationEventMulticaster.multicastEvent(driverOnlineEvent);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //上班成功
            instance.setData(driver.getStatus());

            //驾驶员上线推送监管平台
            superviceService.pushTjyy(driver);
            //推送驾驶员和车辆定位信息
            //superviceService.SjwzMessage(driver,"SJSX");
            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver online error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 设置司机目前为下线状态
     *
     * @param employToken
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "driver/api/rest/v4/offline", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport offline(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            try {
                ServiceSetting serviceSetting = ServiceUtil.checkOpen();

                if (serviceSetting.isDaijia()) {
                    Long daijiaAmount = orderService.countActivedOrdersByDriver(driver.getId());
                    if (daijiaAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_DAIJIA_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isZhuanche()) {
                    Long zhuancheAmount = zhuancheService
                        .countActivedOrdersByDriver(driver.getId());
                    if (zhuancheAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_ZHUANCHE_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isPaotui()) {
                    Long paotuiAmount = errandService.countBusyAmount(driver.getId());
                    if (paotuiAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_PAOTUI_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isFreight()) {
                    Long freightAmount = freightService.countActivedOrdersByDriver(driver.getId());
                    if (freightAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_FREIGHT_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isZhuanxian()) {
                    Long zhuanxianAmount = zhuanxianService
                        .countActivedOrdersByDriver(driver.getId());
                    if (zhuanxianAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_ZHUANXIAN_ORDER_ERROR);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            driver.setStatus(Driver.DRIVER_OFFLINE);
            driverService.updateStatusAndJobStatus(Driver.DRIVER_OFFLINE, null, driver.getId());

            DriverOfflineEvent offlineEvent = new DriverOfflineEvent(driver);
            applicationEventMulticaster.multicastEvent(offlineEvent);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //上班成功
            instance.setData(Driver.DRIVER_OFFLINE);

            //驾驶员上线推送监管平台
            superviceService.pushTjyy(driver);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver offline error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 设置司机目前为注销状态
     *
     * @param employToken
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/logout", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport logout(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            try {
                ServiceSetting serviceSetting = ServiceUtil.checkOpen();

                if (serviceSetting.isDaijia()) {
                    Long daijiaAmount = orderService.countActivedOrdersByDriver(driver.getId());
                    if (daijiaAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_DAIJIA_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isZhuanche()) {
                    Long zhuancheAmount = zhuancheService
                        .countActivedOrdersByDriver(driver.getId());
                    if (zhuancheAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_ZHUANCHE_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isPaotui()) {
                    Long paotuiAmount = errandService.countBusyAmount(driver.getId());
                    if (paotuiAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_PAOTUI_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isFreight()) {
                    Long freightAmount = freightService.countActivedOrdersByDriver(driver.getId());
                    if (freightAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_FREIGHT_ORDER_ERROR);
                    }
                }

                if (serviceSetting.isZhuanxian()) {
                    Long zhuanxianAmount = zhuanxianService
                        .countActivedOrdersByDriver(driver.getId());
                    if (zhuanxianAmount > 0) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.HAS_ACTIVED_ZHUANXIAN_ORDER_ERROR);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            driverLoginService.delete(driverLogin.getId());
            driver.setStatus(Driver.DRIVER_OFFLINE);
            driverService.updateStatusAndJobStatus(Driver.DRIVER_OFFLINE, null, driver.getId());

            DriverOfflineEvent offlineEvent = new DriverOfflineEvent(driver);
            applicationEventMulticaster.multicastEvent(offlineEvent);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //上班成功
            instance.setData(Driver.DRIVER_OFFLINE);

            //驾驶员上线推送监管平台
            superviceService.pushTjyy(driver);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver offline error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 获取服务人员
     *
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/getEmploy", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getDriver(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {
            Setting setting = settingUtils.get();
            Company company = companyService.findOne(driver.getCompanyId());

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("createTime", driver.getCreated().getTime());
            map.put("id", driver.getId());
            map.put("name", driver.getName());
            map.put("realName", driver.getRealname());
            map.put("userName", driver.getUsername());
            map.put("phone", driver.getPhone());
            map.put("companyAbbreviation", company.getAbbreviation());
            map.put("companyTelephone", company.getTelephone());
            map.put("virtual", driver.getVirtual());
            map.put("starLevel", driver.getStarLevel());
            map.put("status", driver.getStatus());
            map.put("longitude", driver.getLongitude());
            map.put("latitude", driver.getLatitude());
            map.put("driverJobType", driver.getDriverJobType());
            map.put("workCar", driver.isWorkCar());
            map.put("companyId", driver.getCompanyId());
            map.put("bankName", driver.getBankName());
            map.put("bankNo", driver.getBankNo());
            map.put("skrName", driver.getSkrName());
            map.put("remarks", setting.getRemarks());
            if (StringUtils.isNotBlank(driver.getPhoto())) {
                map.put("photo", setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
            } else {
                map.put("photo", null);
            }
            String shareUrl = defaultDriverRebateService.getWeixinShareCodeUrl(driver);
            map.put("shareUrl", shareUrl);

            map.put("bankName", driver.getBankName());
            map.put("bankNo", driver.getBankNo());
            map.put("skrName", driver.getSkrName());

            //查询本月收入 ---- 改成查询可使用代付金额
              /*Calendar calendaer = Calendar.getInstance();
              calendaer.set(Calendar.DAY_OF_MONTH, 1);
              calendaer.set(Calendar.HOUR_OF_DAY, 0);
              calendaer.set(Calendar.MINUTE, 0);
              calendaer.set(Calendar.SECOND, 0);
              Date begin = calendaer.getTime();
              BigDecimal thisMonthInCome = driverPaymentsRecordService.sumInComeByEmployWithDate(driver.getId(), begin, null);*/
            //$$$ 给司机端可代付余额
            BigDecimal helppayMoney = helppayService.getHelppayMoneyById(driver.getId());
            map.put("thisMonthInCome", null != helppayMoney ? helppayMoney.doubleValue() : 0.0);

            //车辆类型
            if (StringUtils.isNotBlank(driver.getDriverJobType()) && driver.getDriverJobType()
                .contains(Driver.DriverJobType.zhuanche.toString())) {
                if (null != driver.getCarId()) {
                    Car car = zhuancheService.findCar(driver.getCarId());
                    if (null != car) {
                        map.put("carName_zhuan", car.getCarName());
                        map.put("carNumber_zhuan", car.getCarNumber());
                        if (null != car.getCarTypeId()) {
                            CarType carType = zhuancheService.findCarType(car.getCarTypeId());
                            if (null != carType) {
                                map.put("carTypeName_zhuan", carType.getTypeName());
                                map.put("carTypeId_zhuan", carType.getId());
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(driver.getDriverJobType()) && driver.getDriverJobType()
                .contains(Driver.DriverJobType.freight.toString())) {
                if (null != driver.getTruckId()) {
                    Truck truck = freightService.findTruck(driver.getTruckId());
                    if (null != truck) {
                        map.put("carName_freight", truck.getName());
                        map.put("carNumber_freight", truck.getCarNumber());
                        map.put("carTypeName_freight", truck.getTruckTypeName());
                    }
                }
            }
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            if (StringUtils.isNotBlank(driver.getDriverJobType()) && driver.getDriverJobType()
                .contains(Driver.DriverJobType.zhuanxian.toString())) {
                if (null != driver.getZhuanxianCarId() && serviceSetting.isZhuanxian()) {
                    com.ybkj.daijia.server.zhuanxian.Car car = zhuanxianService
                        .findCar(driver.getZhuanxianCarId());
                    if (null != car) {
                        map.put("carSeats_zhuanxian", car.getRidepeopleNumber());
                        map.put("carName_zhuanxian", car.getCarName());
                        map.put("carNumber_zhuanxian", car.getCarNumber());
                        List<Line> lines = car.getLines();
                        if (!CollectionUtils.isEmpty(lines)) {
                            map.put("carLineName_zhuanxian", lines.get(0).getName());
                        } else {
                            map.put("carLineName_zhuanxian", "");
                        }
                    }
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(map);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver getEmploy error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }


    /**
     * 获取服务人员
     *
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/getEmploy2", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getEmploy2(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {
            Setting setting = settingUtils.get();
            Company company = companyService.findOne(driver.getCompanyId());

            Map<String, Object> map = new HashMap<String, Object>();
            Date created = driver.getCreated();
            map.put("createTime", created.getTime());
            map.put("id", driver.getId());
            map.put("realName", AesUtil.aesEncrypt(driver.getRealname(), AesUtil.VIPARA));
            map.put("userName", AesUtil.aesEncrypt(driver.getUsername(), AesUtil.VIPARA));
            map.put("phone", AesUtil.aesEncrypt(driver.getPhone(), AesUtil.VIPARA));
            map.put("companyAbbreviation",
                AesUtil.aesEncrypt(company.getAbbreviation(), AesUtil.VIPARA));
            map.put("companyTelephone", company.getTelephone());
            map.put("virtual", driver.getVirtual());
            map.put("starLevel", driver.getStarLevel());
            map.put("status", driver.getStatus());
            map.put("longitude", driver.getLongitude());
            map.put("latitude", driver.getLatitude());
            map.put("driverJobType", driver.getDriverJobType());
            map.put("workCar", driver.isWorkCar());
            map.put("companyId", driver.getCompanyId());
            if (StringUtils.isNotBlank(driver.getPhoto())) {
                map.put("photo", setting.getWebUrl() + "/upload/driver/" + driver.getPhoto());
            } else {
                map.put("photo", null);
            }
            String shareUrl = defaultDriverRebateService.getWeixinShareCodeUrl(driver);
            map.put("shareUrl", shareUrl);

            map.put("bankName", driver.getBankName());
            if (null != driver.getBankNo()) {
                map.put("bankNo", AesUtil.aesEncrypt(driver.getBankNo(), AesUtil.VIPARA));
            }
            map.put("skrName", driver.getSkrName());

            // 查询本月收入
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.DAY_OF_MONTH, 1);
            calendaer.set(Calendar.HOUR_OF_DAY, 0);
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date begin = calendaer.getTime();
            BigDecimal thisMonthInCome = driverPaymentsRecordService
                .sumInComeByEmployWithDate(driver.getId(), begin, null);
            map.put("thisMonthInCome", thisMonthInCome);

            // 车辆类型
            if (StringUtils.isNotBlank(driver.getDriverJobType()) && driver.getDriverJobType()
                .contains(Driver.DriverJobType.zhuanche.toString())) {
                if (null != driver.getCarId()) {
                    Car car = zhuancheService.findCar(driver.getCarId());
                    if (null != car) {
                        map.put("carName_zhuan", car.getCarName());
                        map.put("carNumber_zhuan",
                            AesUtil.aesEncrypt(car.getCarNumber(), AesUtil.VIPARA));
                        if (null != car.getCarTypeId()) {
                            CarType carType = zhuancheService.findCarType(car.getCarTypeId());
                            if (null != carType) {
                                map.put("carTypeName_zhuan", carType.getTypeName());
                                map.put("carTypeId_zhuan", carType.getId());
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(driver.getDriverJobType()) && driver.getDriverJobType()
                .contains(Driver.DriverJobType.freight.toString())) {
                if (null != driver.getTruckId()) {
                    Truck truck = freightService.findTruck(driver.getTruckId());
                    if (null != truck) {
                        map.put("carName_freight", truck.getName());
                        map.put("carNumber_freight",
                            AesUtil.aesEncrypt(truck.getCarNumber(), AesUtil.VIPARA));
                        map.put("carTypeName_freight", truck.getTruckTypeName());
                    }
                }
            }
            if (StringUtils.isNotBlank(driver.getDriverJobType()) && driver.getDriverJobType()
                .contains(Driver.DriverJobType.zhuanxian.toString())) {
                if (null != driver.getZhuanxianCarId()) {
                    com.ybkj.daijia.server.zhuanxian.Car car = zhuanxianService
                        .findCar(driver.getZhuanxianCarId());
                    if (null != car) {
                        map.put("carName_zhuanxian", car.getCarName());
                        map.put("carNumber_zhuanxian",
                            AesUtil.aesEncrypt(car.getCarNumber(), AesUtil.VIPARA));
                        List<Line> lines = car.getLines();
                        if (!CollectionUtils.isEmpty(lines)) {
                            map.put("carLineName_zhuanxian", lines.get(0).getName());
                        } else {
                            map.put("carLineName_zhuanxian", "");
                        }
                    }
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(map);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver getEmploy error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }


    /**
     * 获取设备信息
     *
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/getDeviceInfo", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getDeviceInfo(DeviceInfoData data) {

        DriverLogin driverLogin = driverLoginService.selectByToken(data.getEmployToken());

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            //推送
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "deviceinfo");
            jsonObject.put("driverId", driver.getId());
            jsonObject.put("networkType", data.getNetworkType());
            jsonObject.put("mobileVersion", data.getMobileVersion());
            jsonObject.put("operatorName", data.getOperatorName());
            jsonObject.put("systemVersion", data.getSystemVersion());
            jsonObject.put("ip", data.getIp());
            jsonObject.put("gps", data.isGps());
            jsonObject.put("root", data.isRoot());
            jsonObject.put("runningBackground", data.isRunningBackground());
            jsonObject.put("wifi", data.isWifi());
            Company mainCompany = companyService.getMain();
            Company driverCompany = companyService.findOne(driver.getCompanyId());
            WebSocketSend
                .boardcastToCompany(jsonObject, driverCompany.getId(), mainCompany.getId());

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver getDeviceInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /***
     *
     * @param employToken 司机token
     * @param longitude 维度
     * @param latitude  经度
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/getSettings", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getSettings(String employToken, Double longitude, Double latitude) {

        Driver driver = null;
        if (StringUtils.isNotBlank(employToken)) {
            DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

            if (null == driverLogin) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
            }

            if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
            }

            driver = driverService.findOne(driverLogin.getDriverId());

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Setting setting = settingUtils.get();
        ServiceSetting serviceSetting = ServiceUtil.checkOpen();
        map.put("allowRushOrder", setting.isAllowRushOrder());
        map.put("allowWorkCar", setting.isAllowWorkCar());
        map.put("allowWorkCarZhuandan", setting.isAllowWorkCarZhuandan());
        map.put("allowDriverZhuandan", setting.isAllowDriverZhuandan());
        map.put("allowDriverCancel", setting.isAllowDriverCancel());
        map.put("mustToPlace", setting.isMustToPlace());
        map.put("mustMemberInfo", setting.isMustMemberInfo());
        map.put("allowModifyCash", setting.isAllowModifyCash());
        map.put("allowBaoxiao", setting.isAllowBaoxiao());
        map.put("employApplyImgNessesary", setting.isEmployApplyImgNessesary());
        map.put("openHelpPay", setting.isOpenHelpPay());
        map.put("justPrice", setting.isJustPrice());
        map.put("errandFixPrice", setting.isPaotuiFixPrice());
        map.put("insurancesShow", setting.isInsurancesShow());
        map.put("lowestWorkVirtual", setting.getLowestWorkVirtual());
        map.put("payCash1", setting.getPayCash1());
        map.put("payCash2", setting.getPayCash2());
        map.put("payCash3", setting.getPayCash3());
        map.put("bookTimeZhuanxian", setting.getBookTimeZhuanxian());
        map.put("moneyBase", setting.getMoenyBase());
        map.put("startQuota", setting.getStartQuota());
        map.put("endQuota", setting.getEndQuota());
        map.put("remarks", setting.getRemarks());
        map.put("doubleFactor", setting.isDoubleFactor());

        if (null != driver) {
            map.put("driverJobType", driver.getDriverJobType());
            map.put("workCar", driver.isWorkCar());
            map.put("starLevel", driver.getStarLevel());
            //分享设置
            Company company = companyService.findOne(driver.getCompanyId());
            map.put("shareTitle", company.getIntroduceTitle2());
            map.put("shareContent", company.getIntroduceContent2());
            DriverRebate driverRebate = driverRebateService.findByDriverId(driver.getId());
            if (null != driverRebate) {
                map.put("showContent", driverRebate.getContent());
            } else {
                map.put("showContent", "");
            }

            map.put("djxFee", company.getDjxFee());
            map.put("ywxFee", company.getYwxFee());
            map.put("allowPayRule", company.getAllowPayRule());
            map.put("allowDjx", company.getAllowDjx());
            map.put("allowYwx", company.getAllowYwx());
            map.put("djxContent", company.getDjxContent());
            map.put("ywxContent", company.getYwxContent());
        }

        List<Company> companys = companyService.findAll();
        List<Map<String, Object>> companysMapList = new ArrayList<Map<String, Object>>();
        if (null != longitude && null != latitude) {
            String city = "";
            try {
                city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
            } catch (Exception e) {

            }
            for (Company company : companys) {
                Map<String, Object> companyMap = new HashMap<String, Object>();
                companyMap.put("id", company.getId());
                companyMap.put("name", company.getAbbreviation());
                if (StringUtils.isNotBlank(city) && city.equals(company.getCityName())) {
                    companyMap.put("sort", 0);
                } else {
                    if (company.isCompanyType()) {
                        companyMap.put("sort", 1);
                    } else {
                        companyMap.put("sort", 2);
                    }
                }
                companysMapList.add(companyMap);
            }
        }
        Collections.sort(companysMapList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                return arg0.get("sort").toString().compareTo(arg1.get("sort").toString());
            }
        });
        map.put("companys", companysMapList);

        try {
            Properties prop = PropertiesLoaderUtils.loadAllProperties("config.properties");
            String daijia = prop.getProperty("function.daijia.open");
            String zhuanche = prop.getProperty("function.zhuanche.open");
            String gasstation = prop.getProperty("function.gasstation.open");
            String zuche = prop.getProperty("function.zuche.open");
            String paotui = prop.getProperty("function.paotui.open");
            String freight = prop.getProperty("function.freight.open");
            String partner = prop.getProperty("function.partner.open");
            String zhuanxian = prop.getProperty("function.zhuanxian.open");
            boolean djsq = Boolean.valueOf(prop.getProperty("function.djsq.open"));//代驾神器
            map.put("daijia", Boolean.valueOf(daijia));
            map.put("zhuanche", Boolean.valueOf(zhuanche));
            map.put("zuche", Boolean.valueOf(zuche));
            map.put("paotui", Boolean.valueOf(paotui));
            map.put("freight", Boolean.valueOf(freight));
            map.put("partner", Boolean.valueOf(partner));
            map.put("zhuanxian", Boolean.valueOf(zhuanxian));
            map.put("gasstation", Boolean.valueOf(gasstation));

            if (!djsq) {
                map.put("allowPayRule", Boolean.FALSE);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        boolean aliPay = true;
        boolean weixinPay = true;
        boolean unionPay = true;
        boolean bestPay = true;
        if (StringUtils.isBlank(setting.getAlipayPartnerID()) || StringUtils
            .isBlank(setting.getAlipaySellerID()) || StringUtils
            .isBlank(setting.getAlipayPartnerPrivKey())) {
            aliPay = false;
        }
        if (StringUtils.isBlank(setting.getWxAppIDEmploy()) || StringUtils
            .isBlank(setting.getWxAppSecretEmploy()) || StringUtils
            .isBlank(setting.getWxPartnerIDEmploy()) || StringUtils
            .isBlank(setting.getWxPartnerKeyEmploy())) {
            weixinPay = false;
        }
        if (StringUtils.isBlank(setting.getMerId()) || StringUtils.isBlank(setting.getAcpProdEnc())
            || StringUtils.isBlank(setting.getAcpProdMiddle()) || StringUtils
            .isBlank(setting.getAcpProdRoot())
            || StringUtils.isBlank(setting.getAcpsdkSignCertPath()) || StringUtils
            .isBlank(setting.getAcpsdkSignCertPwd())) {
            unionPay = false;
        }
        if (StringUtils.isBlank(setting.getMerchantId()) || StringUtils.isBlank(setting.getMerKey())
            || StringUtils.isBlank(setting.getRiskcontrolinfo())) {
            bestPay = false;
        }
        map.put("aliPay", aliPay);
        map.put("weixinPay", weixinPay);
        map.put("unionPay", unionPay);
        map.put("bestPay", bestPay);

        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(map);

        return instance;
    }

    /***
     * 司机注册测试接口
     * @created zhyu
     * @date 2019-12-19 12:36:28
     * @param photoFile 头像
     * @param idCardPhotoFile   身份证正面图片
     * @param backOfIdCardPhotoFile 身份证反面图片
     * @param licenseFile   行驶证图片
     * @param qualificationPhotoFile 网约车资格证图片
     * @param copy  身份证照片是否是复印件
     * @param remake    身份证照片是否是翻拍
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "driver/api/rest/employApply", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport employApplyTemp(MultipartFile photoFile, MultipartFile idCardPhotoFile, MultipartFile backOfIdCardPhotoFile, MultipartFile licenseFile, MultipartFile qualificationPhotoFile,
        DriverApply driverApply, @RequestParam(value = "copy", required = false) Boolean copy, @RequestParam(value = "remake", required = false) Boolean remake) {
        driverApplyService.driverAppApply(req, photoFile, idCardPhotoFile, backOfIdCardPhotoFile, licenseFile, qualificationPhotoFile, driverApply, copy, remake);
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
        return instance;
    }


    /**
     * 获取验证码
     *
     * @param phone 手机号
     * @return
     */
    @RequestMapping(value = "driver/api/rest/v4/getCode", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getCode(HttpServletRequest request, String phone) {

        logger.debug("recv phone:{}", phone);

        // 短信攻击验证判断
        String user_agent = request.getHeader("user-agent");
        if (user_agent.indexOf("okhttp") == -1 && user_agent.indexOf("yimidaijia_client_ios") == -1
            && user_agent.indexOf("Android") == -1 && user_agent.indexOf("iPhone") == -1) {
            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
        }

        if (StringUtils.isBlank(phone)) {
            return ResultTransport.getErrorBy(ErrorConstant.PHONE_NULL_ERROR);
        }

        Driver driver = driverService.findByUsername(phone);
        if (driver == null) {
            driver = driverService.findByPhone(phone);
        }
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }
        phone = driver.getPhone();

        return getCodeFunc(phone, driver);

    }

    private ResultTransport getCodeFunc(String phone, Driver driver) {
        String regex = "^[0-9]*$";
        if (!Pattern.matches(regex, phone)) {
            return ResultTransport.getErrorBy(ErrorConstant.PHONE_WRONG_ERROR);
        }

        try {

            Map<String, Object> map = driverService.getCodeV3(phone, driver);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            if (null == map) {
                instance.setCode(500);
                instance.setData("发送短信失败");
            } else {
                instance.setCode(0);
                instance.setData(map);
            }

            return instance;

        } catch (Exception e) {
            logger.error("api v3 member getCode error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

}
